<?php

if(!defined('IN_ECS'))
{
	die('Hacking attempt');
}

class cls_mysql
{
	var $link_id = NULL;
	var $settings = array();
	var $queryCount = 0;
	var $queryTime = '';
	var $queryLog =array();
	
	var $max_cache_time = 300;
	var $cache_data_dir = 'temp/query_caches/';
	var $root_path ='';
	
	var $error_message = array();
	var $platform = '';
	var $version = '';
	var $dbhash = '';
	var $starttime = 0;
	var $timeline  =0;
	var $timezone =0;

	var $mysql_config_cache_file_time = 0;
	var $mysql_disable_cache_tables = array();
	
	function __construct($dbhost,$dbuser,$dbpw,$dbname='',$charset='gbk',$pconnect = 0,$quiet = 0)
	{
		$this->cls_mysql($dbhost,$dbuser,$dbpw,$dbname,$charset,$pconnect,$quiet);
	}
	
	function cls_mysql($dbhost,$dbuser,$dbpw,$dbname = '',$charset = 'gbk',$pconnect = 0,$quiet = 0)
	{
		if(defined('EC_CHARSET'))
		{
			$charset =strtolower(str_replace('-', '', EC_CHARSET));
		}
		
		if(defined('ROOT_PATH') && !$this->root_path)
		{
			$this->root_path = ROOT_PATH;
		}
		
		if($quiet)
		{
			$this->connect($dbhost,$dbuser,$dbpw,$dbname,$charset,$pconnect,$quiet);
		}else{
			$this->settings = array(
									'dbhost'		=>$dbhost,
									'dbuser'		=>$dbuser,
									'dbpw'			=>$dbpw,
									'dbname'		=>$dbname,
									'charset'		=>$charset,
									'pconnect'		=>$pconnect
			);
		}
	}
	
	function connect($dbhost,$dbuser,$dbpw,$dbname='',$charset='utf8',$pconnect=0,$quiet=0)
	{
		if($pconnect)
		{
			if(!($this->link_id = @mysql_pconnect($dbhost,$dbuser,$dbpw)))
			{
				if(!$quiet)
				{
					$this->ErrorMsg("Cant't pConnect MySQL Server($dbhost)!");
				}
				return false;
			}
		}else{
			if(PHP_VERSION >= '4.2')
			{
				$this->link_id = @mysql_connect($dbhost,$dbuser,$dbpw,true);
			}else{
				$this->link_id = @mysql_connect($dbhost,$dbuser,$dbpw);
				mt_srand((double)microtime() * 1000000);
			}
			if(!$this->link_id)
			{
				if(!$quiet)
				{
					$this->$ErrorMsg("Cant't connect MySQL Server($dbhost)!");
				}
				return false;
			}
		}
		
		$this->dbhash = md5($this->root_path . $dbhost . $dbuser . $dbpw . $dbname);
		$this->version = mysql_get_server_info($this->link_id);
		
		if($this->version>'4.1')
		{
			if($charset != 'latin1')
			{
				mysql_query("set character_set_connection=$charset,character_set_results=$charset,character_set_client=binary",$this->link_id);
			}
			if($this->version>'5.0.1')
			{
				mysql_query("set sql_mode=''",$this->link_id);
			}
		}
		
		$sqlcache_config_file = $this->root_path . $this->cache_data_dir . 'sqlcache_config_file_' . $this->dbhash . '.php';
		
		@include($sqlcache_config_file);
		
		$this->starttime = time();
		
		if($this->max_cache_time && $this->starttime > $this->mysql_config_cache_file_time + $this->max_cache_time)
		{
			if($dbhost != '.')
			{
				$result = mysql_query("show variables like 'basedir'",$this->link_id);
				$row =mysql_fetch_assoc($result);
				if(!empty($row['Value']{1}) && $row['Value']{1} == ':' && !empty($row['Value']{2}) && $row['Value']{2}=="\\")
				{
					$this->platform = 'WINDOWS';
				}
				else 
				{
					$this->platform = 'OTHER';
				}
			}
			else 
			{
				$this->platform = 'WINDOWS';
			}
			
			if($this->platform = 'OTHER' && ($dbhost != '.' && strtolower($dbhost)!= 'localhost:3306' && $dbhost != '127.0.0.1:3306') ||
			(PHP_VERSION >='5.1' && date_default_timezone_get()=='UTC'))   
			{
				$result = mysql_query("select UNIX_TIMESTAMP() as timeline,unix_timestamp('" . date('Y-m-d H:i:s',$this->starttime) . "') as timezone",$this->link_id);
				$row =mysql_fetch_assoc($result);
				
				if($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306')
				{
					$this->timeline = $this->starttime - $row['timeline']; 
				}
				
				if(PHP_VERSION >='5.1' && date_default_timezone_get() == 'UTC')
				{
					$this->timezone = $this->starttime - $row['timezone'];
				}
			}
			
			$content = '<' ."?php\r\n" .
						'$this->mysql_config_cache_file_time = '.$this->starttime . ";\r\n" .
						'$this->timeline = '.$this->timeline .";\r\n" .
						'$this->timezone = '.$this->timezone . ";\r\n" .
						'$this->platform = '. "'" . $this->platform . "';\r\n?" . '>';
			
			@file_put_contents($sqlcache_config_file, $content);
		}
		
		if($dbname)
		{
			if(mysql_select_db($dbname,$this->link_id) === false)
			{
				if(!$quiet)
				{
					$this->ErrorMsg("Cant't select MySQL database($dbname)!");
				}
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{
			return true;
		}
	}
	
	function select_database($dbname)
	{
		return mysql_select_db($dbname,$this->link_id);
	}
	
	function set_mysql_charset($charset)
	{
		if($this->version>'4.1')
		{
			if(in_array(strtolower($charset), array('gbk','big5','utf-8','utf8')))
			{
				$charset = str_replace('-', '', $charset);
			}
			if($charset != 'latin1')
			{
				mysql_query("set character_set_connection=$charset,character_set_results=$charset,character_set_client=binary",$this->link_id);
			}
		}
	}
	
	function fetch_array($query,$result_type = MYSQL_ASSOC)
	{
		return mysql_fetch_array($query,$result_type);
	}
	
	function query($sql,$type='')
	{
		if($this->link_id == NULL)
		{
			$this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'],$this->settings['dbname'],$this->settings['charset'],$this->settings['pconnect']);
			$this->settings = array();
		}
		
		if($this->queryCount++ <=99)
		{
			$this->queryLog[] = $sql;
		}
		
		if($this->queryTime == '')
		{
			if(PHP_VERSION >= '5.0.0')
			{
				$this->queryTime = microtime(true);
			}
			else 
			{
				$this->queryTime = microtime();
			}
		}
		
		if(PHP_VERSION >= '4.3' && time() > $this->starttime +1)
		{
			mysql_ping($this->link_id);
		}
		
		if(!($query = mysql_query($sql,$this->link_id)) && $type != 'SILENT')
		{
			$this->error_message[]['message'] = 'MySQL Query Error';
			$this->error_message[]['sql'] = $sql;
			$this->error_message[]['error'] = mysql_error($this->link_id);
			$this->error_message[]['errno'] = mysql_errno($this->link_id);
			
			$this->ErrorMsg();
			return false;
		}
		
		return $query;
	}
	
	function affected_rows()
	{
		return mysql_affected_rows($this->link_id);
	}
	
	function error()
	{
		return mysql_error($this->link_id);
	}

	function errno()
	{
		return mysql_errno($this->link_id);
	}
	
	function result($query,$row)
	{
		return @mysql_result($query, $row);
	}
	
	function num_rows($query)
	{
		return mysql_num_rows($query);
	}
	
	function num_fields($query)
	{
		return mysql_num_fields($query);
	}
	
	function free_result($query)
	{
		return mysql_free_result($query);
	}
	
	function insert_id()
	{
		return mysql_insert_id($this->link_id);
	}
	
	function fetchRow($query)
	{
		return mysql_fetch_assoc($query);
	}
	
	function fetch_fields($query)
	{
		return mysql_fetch_field($query);
	}
	
	function version()
	{
		return $this->version;
	}
	
	function ping()
	{
		if(PHP_VERSION >= '4.3')
		{
			return mysql_ping($this->link_id);
		}
		else
		{
			return false;
		}
	}
	
	function escape_string($unescaped_string)
	{
		if(PHP_VERSION >= '4.3')
		{
			return mysql_real_escape_string($unescaped_string);
		}
		else
		{
			return mysql_escape_string($unescaped_string);
		}
	}
	
	function close()
	{
		return mysql_close($this->link_id);
	}
	
	function ErrorMsg($message= '',$sql = '')
	{
		if($message)
		{
			echo "<b>ECSHOP info</b>: $message\n\n<br/><br/>";
		}
		else
		{
			echo "<b>MySQL server error report:";
			print_r($this->error_message);
		}
		exit;
	}
	
	function selectLimit($sql,$num,$start=0)
	{
		if($start == 0)
		{
			$sql .= 'LIMIT '.$num;
		}
		else
		{
			$sql .= 'LIMIT' .$start . ','.$num;
		}
		return $this->query($sql);
	}
	
	function getOne($sql,$limited = FALSE)
	{
		if($limited == true)
		{
			$sql = trim($sql . 'LIMIT 1');
		}
		
		$res = $this->query($sql);
		
		if($res !== false)
		{
			$row =mysql_fetch_row($res);
			if($row !== false)
			{
				return $row[0];
			}
			else
			{
				return '';
			}
		}
		else
		{
			return false;
		}
	}
	
	function getOneCached($sql,$cached = 'FILEFIRST')
	{
		$sql = trim($sql.' LIMIT 1');
		
		$cachefirst = ($cached=='FILEFIRST' || ($cached =='MYSQLFIRST' && $this->platform !='WINDOWS')) && $this->max_cache_time;
		if(!$cachefirst)
		{
			return $this->getOne($sql,ture);
		}
		else 
		{
			$result = $this->getSqlCacheData($sql,$cached);
			if(empty($result['storecache']) == true)
			{
				return $result['data'];
			}
		}
		
		$arr = $this->getOne($sql,true);
		
		if($arr !== false && $cachefirst)
		{
			$this->setSqlCacheData($result,$arr);
		}
		
		return $arr;
	}
	
	function getRow($sql,$limited = false)
	{
		if($limited == true)			//只取出1条记录
		{
			$sql = trim($sql.' LIMIT 1');
		}
		
		$res = $this->query($sql);
		if($res !== false)				//有满足的记录
		{
			return mysql_fetch_assoc($res);		//以关联数组的形式返回
		}
		else
		{
			return false;
		}
	}
	
	function getAll($sql)
	{
		$res = $this->query($sql);
		if($res !== false)
		{
			$arr = array();
			while($row = mysql_fetch_assoc($res))
			{
				$arr[] = $row;
			}
			
			return $arr;
		}
		else
		{
			return false;
		}
	}
	
	
}